import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Row,
  Col,
  DatePicker,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { permissionApi } from '@/services/api';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface Permission {
  id: number;
  code: string;
  name: string;
  description?: string;
  type: string;
  resource?: string;
  status: number;
  sort: number;
  createTime: string;
}

const Permissions: React.FC = () => {
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Permission | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<any>({});
  const [pagination, setPagination] = useState({ 
    current: 1, 
    pageSize: 10, 
    total: 0 
  });

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '权限代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const colors = {
          menu: 'blue',
          button: 'green',
          api: 'orange',
        };
        return <Tag color={colors[type as keyof typeof colors]}>{type}</Tag>;
      },
    },
    {
      title: '资源路径',
      dataIndex: 'resource',
      key: 'resource',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Permission) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此权限吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const fetchPermissions = async (params = {}) => {
    setLoading(true);
    try {
      const finalParams = {
        ...params,
        page: pagination.current,
        pageSize: pagination.pageSize,
      };
      const response = await permissionApi.getPermissions(finalParams);
      const data = response.data || response || {};
      const permissions = data.list || [];
      const total = data.total || 0;
      
      setPermissions(permissions);
      setPagination(prev => ({
        ...prev,
        total
      }));
    } catch (error) {
      message.error('获取权限列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingPermission(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (permission: Permission) => {
    setEditingPermission(permission);
    setModalVisible(true);
    form.setFieldsValue(permission);
  };

  const handleDelete = async (id: number) => {
    try {
      await permissionApi.deletePermission(id);
      message.success('删除成功');
      fetchPermissions(searchParams);
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingPermission) {
        await permissionApi.updatePermission(editingPermission.id, values);
        message.success('更新成功');
      } else {
        await permissionApi.createPermission(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchPermissions(searchParams);
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const handleSearch = (values: any) => {
    const params = { ...values };
    
    // 处理日期范围
    if (values.createTimeRange && values.createTimeRange.length === 2) {
      params.createTimeStart = values.createTimeRange[0].format('YYYY-MM-DD');
      params.createTimeEnd = values.createTimeRange[1].format('YYYY-MM-DD');
      delete params.createTimeRange;
    }
    
    setSearchParams(params);
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    fetchPermissions(params);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
    fetchPermissions();
  };

  useEffect(() => {
    fetchPermissions();
  }, []);

  return (
    <div>
      {/* 查询表单 */}
      <Card title="查询条件" style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="vertical"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词搜索">
                <Input placeholder="权限名/代码/描述" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="name" label="权限名称">
                <Input placeholder="请输入权限名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="code" label="权限代码">
                <Input placeholder="请输入权限代码" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="type" label="权限类型">
                <Select placeholder="请选择类型" allowClear>
                  <Option value="menu">菜单</Option>
                  <Option value="button">按钮</Option>
                  <Option value="api">接口</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="resource" label="资源路径">
                <Input placeholder="请输入资源路径" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="请选择状态" allowClear>
                  <Option value={1}>启用</Option>
                  <Option value={0}>禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="createTimeRange" label="创建时间">
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="sortBy" label="排序字段">
                <Select placeholder="请选择排序字段" allowClear>
                  <Option value="sort">排序值</Option>
                  <Option value="createTime">创建时间</Option>
                  <Option value="updateTime">更新时间</Option>
                  <Option value="name">权限名称</Option>
                  <Option value="type">权限类型</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="sortOrder" label="排序方向">
                <Select placeholder="请选择排序方向" allowClear>
                  <Option value="ASC">升序</Option>
                  <Option value="DESC">降序</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={18}>
              <Form.Item label=" " style={{ marginTop: 4 }}>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    查询
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 主表单 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增权限
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={permissions}
          rowKey="id"
          loading={loading}
          scroll={{ y: 600 }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              const newPagination = { current: page, pageSize: pageSize || 10, total: pagination.total };
              setPagination(newPagination);
              fetchPermissions(searchParams);
            },
          }}
        />

        <Modal
          title={editingPermission ? '编辑权限' : '新增权限'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => form.submit()}
          width={600}
        >
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              name="code"
              label="权限代码"
              rules={[{ required: true, message: '请输入权限代码' }]}
            >
              <Input placeholder="如：user:create" />
            </Form.Item>

            <Form.Item
              name="name"
              label="权限名称"
              rules={[{ required: true, message: '请输入权限名称' }]}
            >
              <Input placeholder="如：创建用户" />
            </Form.Item>

            <Form.Item
              name="type"
              label="权限类型"
              rules={[{ required: true, message: '请选择权限类型' }]}
            >
              <Select placeholder="请选择权限类型">
                <Option value="menu">菜单</Option>
                <Option value="button">按钮</Option>
                <Option value="api">接口</Option>
              </Select>
            </Form.Item>

            <Form.Item name="resource" label="资源路径">
              <Input placeholder="如：/api/users" />
            </Form.Item>

            <Form.Item name="description" label="描述">
              <Input.TextArea rows={3} placeholder="权限描述" />
            </Form.Item>

            <Form.Item name="sort" label="排序" initialValue={0}>
              <Input type="number" />
            </Form.Item>

            <Form.Item name="status" label="状态" initialValue={1}>
              <Select>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default Permissions;